<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? 'Add新增' : 'Update修改'" width="70%" :close-on-click-modal="false">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="160px" :inline="true" @keyup.enter="submitHandle()">
			<el-row>
				<el-col :span="12">
					<el-form-item prop="reversalAmount" label="ReversalAmount 冲销金额" label-width="180px">
						<el-input v-model="dataForm.reversalAmount" placeholder=""></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item prop="currency" label="currency 币种">
						<el-select-v2
							v-model="dataForm.currency"
							filterable
							:options="currencyOptions"
							clearable
							placeholder="please input a keyword"
						/>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item prop="receiptItemsSelfNumber" label="Receipts(self-number) 收款事项(自编号)" label-width="270px">
						<el-input v-model="dataForm.receiptItemsSelfNumber" placeholder=""></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item prop="receiptItemsCntNo" label="ReceiptItems(box number) 收款事项(箱号)" label-width="280px">
						<el-input v-model="dataForm.receiptItemsCntNo" placeholder=""></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item prop="receiptItemsReceiptNumber" label="ReceiptItems(receipt number) 收款事项(收据单号)" label-width="330px">
						<el-input v-model="dataForm.receiptItemsReceiptNumber" placeholder=""></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item prop="receiptItemsCustomerName" label="CollectionMatters(Customers) 收款事项(客户)" label-width="300px">
						<el-select-v2
							v-model="dataForm.receiptItemsCustomerId"
							filterable
							remote
							:remote-method="getClientList"
							:options="clientOptions"
							clearable
							placeholder="please input a keyword"
						/>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item prop="currencyPay" label="Currency of payment收款币种" label-width="200px">
						<el-select-v2
							v-model="dataForm.currencyPay"
							filterable
							:options="currencyOptions"
							clearable
							placeholder="please input a keyword"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item prop="confirmReceivedAmount" label="Confirm the amount received 确认到账金额" label-width="280px">
						<el-input v-model="dataForm.confirmReceivedAmount" placeholder=""></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item prop="arrivalDate" label="Arrival date 到账日期">
						<el-date-picker
							v-model="dataForm.arrivalDate"
							type="date"
							placeholder="please select"
							:shortcuts="store.commonStore.shortcuts"
							value-format="YYYY-MM-DD HH:mm:ss"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item prop="bankAccount" label="bank account到账银行" label-width="260px">
						<el-select-v2
							v-model="dataForm.bankAccount"
							filterable
							:options="bankOptions"
							clearable
							placeholder="please input a keyword"
						/>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col>
					<el-form-item prop="remark" label="Remark 备注">
						<el-input v-model="dataForm.remark" type="textarea" placeholder="备注"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import {  usePayDetailApi, usePayDetailSubmitApi } from '@/api/accountDetail'
import {  selectCustomerList } from '@/api/client'
import { useReceiveApi } from '@/api/receivable'
import {  useSelectRelListApi } from '@/api/dict'
import store from '@/store'

const props = defineProps({
	accountId: {
		type: String
	},
	customerInfo: {
		type: Object
	}
})

let customerId = '', customerName = '';
if(props.customerInfo){
	customerId = props.customerInfo.customerId;
	customerName = props.customerInfo.customerName;
}

const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const dataFormRef = ref()
const dataForm = reactive({
	id: '',
	receivablesId: props.accountId,
	reversalAmount: '',
	currency: '',
	receiptItemsSelfNumber: '',
	receiptItemsCntNo: '',
	receiptItemsReceiptNumber: '',
	receiptItemsCustomerId: customerId,
	receiptItemsCustomerName: customerName,
	currencyPay: '',
	confirmReceivedAmount: '',
	bankAccount: '',
	arrivalDate: '',
	remark: ''
})

// 客户选项下拉
interface ListItem {
  customerId: string
  customerName: string
}

const clientOptions = ref<ListItem[]>([])
const getClientList = (query: string) => {
	let req = {
		page: 1,
		limit: 100,
		customerName: query
	}
	selectCustomerList(req).then(res => {
		let list = res.data.list.map((item)=>{
			return {
				value: item.id,
				label: item.name
			}
		})
		clientOptions.value = list;
	})
}
getClientList('');

// 银行账号选项下拉
const bankOptions = ref([])
const getBankList = (query: string) => {
	let req = {
		page: 1,
		limit: 100,
		dictType: 'bank_account',
		dictLabel: query
	}
	useSelectRelListApi(req).then(res => {
		let list = res.data.map((item)=>{
			return {
				value: item.dictValue,
				label: item.dictLabel
			}
		})
		bankOptions.value = list;
	})
}
getBankList('');

// 币种下拉
const currencyOptions = ref([])
const getCurrencyList = (query: string) => {
	let req = {
		page: 1,
		limit: 100,
		dictType: 'currency',
		dictLabel: query
	}
	useSelectRelListApi(req).then(res => {
		let list = res.data.map((item)=>{
			return {
				value: item.dictValue,
				label: item.dictLabel
			}
		})
		currencyOptions.value = list;
	})
}
getCurrencyList('');

// 表单输入规则限制
const validateNumber = (rule: any, value: any, callback: any) => {
	let isNumber =  value
        .replace(/[^\d.]/g, "")
        .replace(/\.{2,}/g, ".")
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".")
        .replace(/^\./g, "");
  if (value !== '') {
	if (isNumber) {
		callback()
	}else{
		callback(new Error('Please input number'))
	}
  }
}
const dataRules = ref({
	reversalAmount: [{ validator: validateNumber, trigger: 'blur' }],
	confirmReceivedAmount: [{ validator: validateNumber, trigger: 'blur' }]
})

const init = (id?: number) => {
	visible.value = true
	dataForm.id = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	// id 存在则为修改
	if (id) {
		getFollowInfo(id)
	}else{
		if(props.accountId){
			getReceiveInfo(Number(props.accountId))
		}
	}
}

const getFollowInfo = (id: number) => {
	usePayDetailApi(id).then(res => {
		Object.assign(dataForm, res.data)
	})
}
// 获取应收款详情
const getReceiveInfo = (id: any) => {
	useReceiveApi(id).then(res => {
		let data = res.data;
		dataForm.receiptItemsSelfNumber = data.jobNumber;
		dataForm.receiptItemsCntNo = data.cntNo;
		dataForm.receiptItemsReceiptNumber = data.receiptNo;
	})
}

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
		usePayDetailSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>
